<template>
  <a-page-header :title="$t('101')">
    <template #extra>
      <a-input-search
        v-model:value="state.keyWord"
        :placeholder="$t('103')"
        @search="onSearch"
        @pressEnter="onSearch"
      />
      <a-button @click="loadModelList" :title="$t('104')">{{
        $t("104")
      }}</a-button>
      <a-dropdown-button type="primary"
        >{{ $t("105") }}
        <template #overlay>
          <a-menu @click="handleMenuClick">
            <a-menu-item key="local_data_store"> {{ $t("106") }} </a-menu-item>
            <a-menu-item key="from_data_store"> {{ $t("107") }} </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown-button>
      <a-dropdown-button :disabled="!state.canExport">
        导出
        <template #overlay>
          <a-menu @click="handleMenuClick">
            <a-menu-item key="export_nodata"> {{ $t("108") }} </a-menu-item>
            <a-menu-item key="export_all"> {{ $t("109") }} </a-menu-item>
          </a-menu>
        </template>
      </a-dropdown-button>
      <a-button :disabled="!state.canExport" @click="goImport">导入</a-button>
    </template>
  </a-page-header>
  <a-table
    :columns="colsForModel"
    :data-source="lstModel"
    bordered
    :row-selection="rowSelection"
    size="small"
  >
    <template #bodyCell="{ column, record }">
      <template v-if="column.dataIndex == 'Detail'">
        <a href="#Detail" v-on:click="goEditModel(record.model)">{{
          record.model.name
        }}</a>
        <span style="color: gray; font-size: smaller; margin-left: 8px">{{
          record.model.memo
        }}</span>
      </template>
      <template v-if="column.dataIndex == 'fieldCount'">
        <a href="#Field" v-on:click="goFieldDefine(record.model)">{{
          record.fieldCount
        }}</a>
      </template>
      <template v-if="column.dataIndex == 'shareRequest'">
        <a href="#VisitRequest" v-on:click="goVisitRequest(record.model)">{{
          record.shareRequest
        }}</a>
      </template>
      <template v-if="column.dataIndex == 'tagStatus'">
        <a href="#Tag" v-on:click="goTag(record.model)">{{
          record.tagStatus
        }}</a>
      </template>
      <template v-if="column.dataIndex == 'recordCount'">
        <a href="#RecordCount" v-on:click="goDataView(record.model)">{{
          record.recordCount
        }}</a>
      </template>
      <template v-if="column.dataIndex == 'ruleCount'">
        <a
          href="#RecordRuleCount"
          v-on:click="goRecordValueRule(record.model)"
          >{{ record.ruleCount }}</a
        >
      </template>
      <template v-if="column.dataIndex == 'vgCount'">
        <a href="#VisitGroup" v-on:click="goVisitGroup(record.model)">{{
          record.vgCount
        }}</a>
      </template>
    </template>
  </a-table>
  <a-drawer
    v-model:open="state.popModelConfig"
    :title="$t('110')"
    :bodyStyle="{ padding: '4px' }"
    :headerstyle="{ padding: '4px' }"
  >
    <ModelBasic :model="channel.selectedModel"></ModelBasic>
  </a-drawer>
  <a-drawer
    v-model:open="state.popFieldConfig"
    :title="state.modalTitle"
    width="800px"
    :bodyStyle="{ padding: '4px' }"
    :headerstyle="{ padding: '4px' }"
  >
    <FieldEditor :model="channel.selectedModel"></FieldEditor>
  </a-drawer>
  <a-drawer
    v-model:open="state.popRecordConfig"
    :title="state.modalTitle"
    size="large"
    :bodyStyle="{ padding: '4px' }"
    :headerstyle="{ padding: '4px' }"
  >
    <RecordRule :model="channel.selectedModel"></RecordRule>
  </a-drawer>
  <a-drawer
    v-model:open="state.popVisitGroup"
    :title="state.modalTitle"
    width="800px"
    :bodyStyle="{ padding: '4px' }"
    :headerstyle="{ padding: '4px' }"
  >
    <VisitGroupEditor :model="channel.selectedModel"></VisitGroupEditor>
  </a-drawer>
  <a-drawer
    v-model:open="state.popMrCode"
    :title="state.modalTitle"
    size="large"
    :bodyStyle="{ padding: '4px' }"
    :headerstyle="{ padding: '4px' }"
  >
    <ModelTag :model="channel.selectedModel"></ModelTag>
  </a-drawer>
  <a-drawer
    v-model:open="state.popRequest"
    :title="state.modalTitle"
    size="large"
    :bodyStyle="{ padding: '4px' }"
    :headerstyle="{ padding: '4px' }"
  >
    <ShareRequest ref="refVR" :model="channel.selectedModel"></ShareRequest>
  </a-drawer>
  <a-drawer
    v-model:open="state.popImport"
    :bodyStyle="{ padding: '4px' }"
    :headerstyle="{ padding: '4px' }"
    title="导入"
  >
    <ImportParquet ref="refIP"></ImportParquet>
  </a-drawer>
</template>
<script setup>
import { computed, onMounted, reactive } from "vue";
import ModelBasic from "@/my/ModelBasic.vue";
import FieldEditor from "@/my/FieldEditor.vue";
import CommonDefine from "@/component/CommonDefine";
import { useRouter } from "vue-router";
import RecordRule from "@/my/RecordRule.vue";
import ShareRequest from "@/my/VisitRequest.vue";
import VisitGroupEditor from "@/component/visit/VisitGroupEditor.vue";
import ModelTag from "@/my/ModelTag.vue";
import { useI18n } from "vue-i18n";
import ImportParquet from "./ImportParquet.vue";

const { t } = useI18n();
const router = useRouter();
const appStore = CommonDefine.appStore();
const channel = CommonDefine.channel();
const colsForModel = [
  {
    title: t("112"),
    dataIndex: "Detail",
    sorter: (a, b) =>
      a["model"]["name"].localeCompare(b["model"]["name"], "zh"),
  },
  {
    title: t("113"),
    dataIndex: "fieldCount",
    width: 80,
  },
  {
    title: t("114"),
    dataIndex: "recordCount",
    width: 80,
  },
  {
    title: t("115"),
    dataIndex: "tagStatus",
  },
  {
    title: t("116"),
    dataIndex: "shareRequest",
  },
  {
    title: "记录规则",
    dataIndex: "ruleCount",
  },
  {
    title: "访问组",
    dataIndex: "vgCount",
  },
  {
    title: "订阅数",
    dataIndex: "subscriptionCount",
  },
];
const state = reactive({
  popModelConfig: false,
  popImport: false,
  selectedRowKeys: [],
  canExport: false,
  popFieldConfig: false,
  popRecordConfig: false,
  modalTitle: "",
  popVisitGroup: false,
  popMrCode: false,
  popRequest: false,
  keyWord: "",
});

const rowSelection = computed(() => {
  return {
    type: "radio",
    selectedRowKeys: state.selectedRowKeys,
    onChange: (selectedRowKeys) => {
      state.selectedRowKeys = selectedRowKeys;
      state.canExport = selectedRowKeys && selectedRowKeys.length > 0;
    },
  };
});

const handleMenuClick = (e) => {
  let modelId = state.selectedRowKeys[0];
  switch (e.key) {
    case "local_data_store":
      channel.selectedModel = {};
      state.popModelConfig = true;
      break;
    case "from_data_store":
      channel.selectedModel = { store: {} };
      state.popModelConfig = true;
      break;
    case "export_nodata":
    case "export_all":
      CommonDefine.apiPostArm(
        "/api/v1/model/export",
        {
          modelId,
          withData: e.key === "export_all",
        },
        (d) => {
          fetch("/api/v1/model/download", {
            method: "POST",
            headers: {
              Authorization: `Bearer ${localStorage.getItem("token")}`,
              "Content-Type": "application/json",
            },
            body: JSON.stringify({ modelId }),
          })
            .then((r) => r.blob())
            .then((b) => {
              let downloadUrl = URL.createObjectURL(b);
              let a = document.createElement("a");
              a.href = downloadUrl;
              a.download = `${d}_${e.key}.parquet`;
              document.body.appendChild(a);
              a.click();
              document.body.removeChild(a);
              // 释放创建的 URL
              URL.revokeObjectURL(downloadUrl);
            })
            .catch((error) => {
              console.error("Download error:", error);
            });
        }
      );
      break;
  }
};

const loadRecordCount = () => {
  CommonDefine.apiGetArm(`/api/v1/record/count-record`, (d) => {
    let countMap = new Map();
    Object.entries(d).forEach(([key, value]) => {
      countMap.set(parseInt(key), value);
    });
    lstModel.forEach((record) => {
      record.recordCount = countMap.get(record.model.id);
    });
  });
};

const loadTagStatus = () => {
  CommonDefine.apiGetArm("/api/v1/share/tag-status", (d) => {
    lstModel.forEach((record) => {
      record.tagStatus = d[record.model.id];
    });
  });
};

const lstModel = reactive([]);
const loadModelList = () => {
  CommonDefine.clearArray(lstModel);
  CommonDefine.clearArray(appStore.allMyModels);
  CommonDefine.apiGetArm("/api/v1/model/mine", (d) => {
    d.forEach((item) => {
      item.key = item.model.id;
      item.shareRequest = t("117", [item.reqSum, item.reqHandled]);
      item.model.shareRange = item.shareRangeCode;
      if (CommonDefine.useful(item.model.store)) {
        item.model.store.tbName = item.model.store.remoteKey;
        item.model.store.luSql = item.model.store.logicUsefulSql;
        item.model.store.utsCol = item.model.store.utsKey;
        item.model.store.pkCol = item.model.store.primaryKey;
      }
      lstModel.push(item);
      appStore.allMyModels.push(item);
    });
    if (lstModel.length > 0) {
      loadRecordCount();
      loadTagStatus();
    }
  });
};

const goFieldDefine = (model) => {
  channel.selectedModel = model;
  state.modalTitle = t("118", [model.name]);
  state.popFieldConfig = true;
};

const goRecordValueRule = (model) => {
  channel.selectedModel = model;
  let fn = (fileds) => {
    state.modalTitle = t("119", [model.name]);
    state.popRecordConfig = true;
  };
  CommonDefine.runWithFieldCache(model.id, fn);
};

const goDataView = (model) => {
  channel.selectedModel = model;
  let fn = (fields) => {
    state.modalTitle = t("120", [model.name]);
    router.push("/index/my-model-record");
  };
  CommonDefine.runWithFieldCache(model.id, fn);
};

const goEditModel = (model) => {
  channel.selectedModel = model;
  state.popModelConfig = true;
  state.modalTitle = t("121", [model.name]);
};

const goVisitGroup = (model) => {
  channel.selectedModel = model;
  CommonDefine.runWithFieldCache(model.id, () => {
    state.popVisitGroup = true;
    state.modalTitle = t("122", [model.name]);
  });
};

const goVisitRequest = (model) => {
  channel.selectedModel = model;
  state.modalTitle = t("123", [model.name]);
  state.popRequest = true;
};

const goTag = (model) => {
  channel.selectedModel = model;
  state.modalTitle = t("124", [model.name]);
  state.popMrCode = true;
};

const onSearch = () => {
  CommonDefine.clearArray(lstModel);
  if (CommonDefine.isStringValue(state.keyWord)) {
    appStore.allMyModels.forEach((item) => {
      if (
        item.model.name.indexOf(state.keyWord) >= 0 ||
        (item.model.memo && item.model.memo.indexOf(state.keyWord) >= 0)
      ) {
        lstModel.push(item);
      }
    });
  } else {
    appStore.allMyModels.forEach((item) => lstModel.push(item));
  }
};

const goImport = () => {
  let modelId = state.selectedRowKeys[0];
  channel.selectedModel = { modelId };
  state.popImport = true;
};

onMounted(() => {
  loadModelList();
});
</script>
